package cn.akwangl.controller;

import cn.akwangl.model.SocketMessage;
import cn.akwangl.service.WebSocketServer;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.util.Date;

@Controller
@RequestMapping("/web/socket")
public class WebSocketController {

    /**
     * 页面请求
     *
     * @param cid
     * @return
     */
    @GetMapping("/join/{cid}")
    public ModelAndView socket(@PathVariable("cid") String cid) {
        ModelAndView mav = new ModelAndView("index");
        mav.addObject("cid", cid);
        return mav;
    }

    /**
     * 推送数据接口
     *
     * @param cid
     * @param message
     * @return
     */
    @ResponseBody
    @GetMapping("/send/{cid}/{message}")
    public String pushToWeb(@PathVariable("cid") String cid, @PathVariable("message") String message) {
        try {
            SocketMessage newMessage = new SocketMessage(message, new Date());
            WebSocketServer.sendInfo(newMessage, cid);
        } catch (IOException e) {
            e.printStackTrace();
            return cid + "#" + e.getMessage();
        }
        return cid;
    }
}